import akshare as ak
import pandas as pd
from datetime import datetime, timedelta
import os

# 设置您的市场列表
# markets = ["DCE", "CZC", "SHFE"]  # 示例市场代码
markets = ["SHFE"]  # 示例市场代码

# 获取数据
def fetch_data(start_date, end_date, market):
    return ak.get_futures_daily(start_date=start_date, end_date=end_date, market=market)

# 保存数据到CSV
def save_to_csv(data, symbol, market):
    directory = f'futures_data/{market}'  # 为每个市场创建一个目录
    if not os.path.exists(directory):
        os.makedirs(directory)
    csv_file = os.path.join(directory, f'{symbol}.csv')
    if not os.path.exists(csv_file):
        data.to_csv(csv_file, index=False)
    else:
        data.to_csv(csv_file, mode='a', header=False, index=False)

# 更新数据
def update_data(start_date, end_date, markets):
    for market in markets:
        futures_data = fetch_data(start_date, end_date, market)
        futures_data.columns=['symbol','datetime','open_price','high_price','low_price','close_price','volume','open_interest','turnover','settle','pre_settle','variety']
        symbols = futures_data['symbol'].unique()
        futures_data['local_symbol'] = futures_data['symbol'].apply(lambda x: x + '.' + market)

        for symbol in symbols:
            symbol_data = futures_data[futures_data['symbol'] == symbol]
            save_to_csv(symbol_data, symbol, market)

# 设定日期变量
start_date = (datetime.now() - timedelta(days=365)).strftime('%Y%m%d')
end_date = datetime.now().strftime('%Y%m%d')

# 执行更新数据函数
update_data(start_date, end_date, markets)
